package com.gxa.learning.pc.interceptor;

import com.gxa.learning.core.common.ExceptionCode;
import com.gxa.learning.core.exception.BusinessException;
import com.gxa.learning.core.pojo.User;
import com.gxa.learning.core.util.StringUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URL;
import java.util.HashMap;

/**
 * token拦截器
 *
 * @author YXQ
 * @date 2021/12/14 21:15
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 这里做权限验证的代码
        String requestUri = request.getRequestURI();
        System.out.println("------" + requestUri + "被拦截");
        // 验证token
        // 创建session对象
        HttpSession session = request.getSession();
        // 从请求头获取token
        String token = request.getHeader("token");
        System.out.println("------" + "前端token:   " + token);
        // 拿到token后传给sso服务器做通信，校验
        // 获取RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();
        // 待访问的URL
        // URL url = new URL("http://localhost:8089/user/queryUserByToken");
        String url = "http://www.lijianmin.top:8089/user/queryUserByToken";
        // String url = "http://47.108.53.165:8089/user/queryUserByToken";
        // 设置请求头，请求类型为json
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 设置请求参数
        MultiValueMap multiValueMap = new LinkedMultiValueMap();
        multiValueMap.add("token",token);
        //用HttpEntity封装整个请求报文
        // 开始调用
        // 参数1：目标请求地址
        // 参数2：请求体
        // 参数3：目标请求接口的返回值类型（execute接口的返回值类型）
        User user = restTemplate.postForObject(url.toString(), multiValueMap,User.class);
        // 如果返回的user是个空的表示登录失败(校验token失败)
        if (user == null || user.getId() == null){
            // 登录已过期
            throw new BusinessException(ExceptionCode.TOKEN_FAILDE);
        }
        System.out.println("放行了");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
